package com.terry.bootdemo.web.Interceptor;

import com.terry.bootdemo.web.annotation.TokenAnnotation;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.UUID;


public class TokenIntercepter extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            TokenAnnotation annotation = method.getAnnotation(TokenAnnotation.class);
            if (annotation != null) {
                boolean needSaveSession = annotation.save();
                if (needSaveSession) {
                    HttpSession session =  request.getSession();
                 String uuid=   UUID.randomUUID().toString();
                    session.setAttribute("formtoken", uuid);
                }
                boolean needRemoveSession = annotation.remove();
                if (needRemoveSession) {
                    if (isRepeatSubmit(request)) {
                        //response.sendRedirect("/test/test");
                        RequestDispatcher requestDispatcher =request.getRequestDispatcher("/home");
                        //调用forward()方法，转发请求
                        requestDispatcher.forward(request,response);
                        return false;
                    }
                    request.getSession(false).removeAttribute("formtoken");
                }
            }
            return true;
        } else {
            return super.preHandle(request, response, handler);
        }
    }

    private boolean isRepeatSubmit(HttpServletRequest request) {
        int a=0;
 switch (a){
     case 1:
         System.out.println("hsh");
         break;
     case 2:
         System.out.println(2);
         break;
         default:
             System.out.println("default");
             break;
 }

        HttpSession session =  request.getSession(false);
       String  serverToken= (String) session.getAttribute("formtoken");
        if (serverToken == null) {
            return true;
        }
        String clinetToken = request.getParameter("formtoken");
        if (StringUtils.isEmpty(clinetToken)) {
            return true;
        }
        if (!serverToken.equals(clinetToken)) {
            return true;
        }
        return false;
    }



}
